package com.loveshes.springbootstudy1.controller;

import com.loveshes.springbootstudy1.common.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ControllerExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);

    @ExceptionHandler({HttpMessageNotReadableException.class,HttpMediaTypeNotSupportedException.class})
    public Object requestFormatException(Exception e){
        logger.error(e.getMessage());
        return JsonResult.fail().message("请检查是否使用json格式请求，并确保请求参数类型和格式正确");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Object httpRequestMethodNotSupportedException(){
        return JsonResult.fail().message("请使用post请求");
    }

    // 参数格式检验
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Object methodArgumentNotValidException(MethodArgumentNotValidException e) {
        return JsonResult.fail().message(e.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    // 参数转化失败
    @ExceptionHandler(BindException.class)
    public Object httpException(BindException ex){
        return JsonResult.fail().message(ex.getBindingResult().getFieldErrors().get(0).getDefaultMessage());
    }

    // 兜底处理
    @ExceptionHandler(Exception.class)
    public Object httpException(Exception ex){
        logger.error("访问出错", ex);
        return JsonResult.fail().message("系统异常,请联系管理员查看");
    }

}
